<?php 
if (isset($set_modules) && $set_modules == TRUE)
{
    $i = isset($modules) ? count($modules) : 0;

    $modules[$i]['code']    = basename(__FILE__, '.class.php');
    $modules[$i]['name']    = L('tenpay', '', 'pay');   
    $modules[$i]['desc']    = L('tenpay_tip', '', 'pay');
    $modules[$i]['is_cod']  = '0';
    $modules[$i]['is_online']  = '1';
    $modules[$i]['author']  = 'Old Sea';
    $modules[$i]['website'] = 'http://www.ps2htm.com';
    $modules[$i]['version'] = '1.0.0';
    $modules[$i]['config']  = array(
     	array('name' => 'tenpay_account','type' => 'text','value' => ''),
        array('name' => 'tenpay_key','type' => 'text','value' => ''),
       // array('name' => 'tenpay_partner','type' => 'text','value' => ''),
        array('name' => 'service_type_ten','type' => 'select','value' => '0'),
    );

    return;
}
pc_base::load_app_class('pay_abstract','','0');

class Tenpay extends paymentabstract{
	
	public function __construct($config = array()) {	
		if (!empty($config)) $this->set_config($config);
		
/*	    if ($this->config['service_type_ten']==1) $this->config['service'] = 'trade_create_by_buyer';
		elseif($this->config['service_type_ten']==2) $this->config['service'] = 'create_direct_pay_by_user';
        else $this->config['service'] = 'create_partner_trade_by_buyer';*/	
        
		$this->config['gateway_url'] = 'https://www.tenpay.com/cgi-bin/v1.0/pay_gate.cgi';
		$this->config['gateway_method'] = 'GET';
		$this->config['notify_url'] = return_url('tenpay',1);
		$this->config['return_url'] = return_url('tenpay');
		//print_r($this->config);
		pc_base::load_app_func('tenpay');
	}

	public function getpreparedata() {	
	
		if($this->config['service_type_ten']==0)//担保交易
		{
			
			$cmdno = "12";
			$mch_desc="交易说明";
			$mch_name="商品名称";
			/* 物流公司或物流方式说明 */
			$transport_desc = "";
			
			/* 需买方另支付的物流费用,以分为单位 */
			$transport_fee = "";
			$date = date("Ymd");
			$bargainor_id = $this->config['tenpay_account'];
			/**/
			$strTime = date("His");
			//4位随机数
			$randNum = rand(1000, 9999);
			//10位序列号,可以自行调整。
			$strReq = $strTime . $randNum;
			/* 商家订单号,长度若超过32位，取前32位。财付通只记录商家订单号，不保证唯一。 */
			$sp_billno = $strReq;
			/* 财付通交易单号，规则为：10位商户号+8位时间（YYYYmmdd)+10位流水号 */
			$transaction_id = date("YmdHis").$randNum;
			/**/
			$total_fee = $this->product_info['price']*100;
			$fee_type = "1";
			$return_url = $this->config['return_url'];
			$attach = $this->order_info['id'];
			$spbill_create_ip = ip();
			$desc = $this->order_info['id'];
			$bank_type = "0";
			$cs = CHARSET;
			$key = $this->config['tenpay_key'];
			
			$prepare_data['attach'] = $attach;
			$prepare_data['cmdno'] = $cmdno;
			$prepare_data["chnid"]=$bargainor_id;						//平台商帐号
			$prepare_data["encode_type"]="2";					//编码类型 1:gbk 2:utf-8
			$prepare_data["mch_desc"]=$mch_desc;				//交易说明
			$prepare_data["mch_name"]=$mch_name;				//商品名称
			$prepare_data["mch_price"]=$total_fee;				//商品总价，单位为分
			$prepare_data["mch_returl"]=$return_url;			//回调通知URL
			$prepare_data["mch_type"]="1";						//交易类型：1、实物交易，2、虚拟交易
			$prepare_data["mch_vno"]=$transaction_id;					//商家的定单号
			$prepare_data["need_buyerinfo"]="2";				//是否需要在财付通填定物流信息，1：需要，2：不需要。
			$prepare_data["seller"]=$bargainor_id;					//卖家财付通帐号
			$prepare_data["show_url"]=$return_url;				//支付后的商户支付结果展示页面
			$prepare_data["transport_desc"]=$transport_desc;	//物流公司或物流方式说明
			$prepare_data["transport_fee"]=$transport_fee;		//需买方另支付的物流费用
			$prepare_data["version"]=2;		//版本号
			$prepare_data['sign'] = tenpay_build_mysign_2($prepare_data,$key,'MD5');
			$prepare_data = ten_arg_sort($prepare_data);
			
		}
		else
		{
			$cmdno = "1";
			$date = date("Ymd");
			$bargainor_id = $this->config['tenpay_account'];
			/**/
			$strTime = date("His");
			//4位随机数
			$randNum = rand(1000, 9999);
			//10位序列号,可以自行调整。
			$strReq = $strTime . $randNum;
			/* 商家订单号,长度若超过32位，取前32位。财付通只记录商家订单号，不保证唯一。 */
			$sp_billno = $strReq;
			/* 财付通交易单号，规则为：10位商户号+8位时间（YYYYmmdd)+10位流水号 */
			$transaction_id = $bargainor_id . $date . $strReq;
			/**/
			$total_fee = $this->product_info['price']*100;
			$fee_type = "1";
			$return_url = $this->config['return_url'];
			$attach = $this->order_info['id'];
			$spbill_create_ip = ip();
			$desc = $this->order_info['id'];
			$bank_type = "0";
			$cs = CHARSET;
			$key = $this->config['tenpay_key'];
				
			$prepare_data['cmdno'] = $cmdno;
			$prepare_data['date'] = $date;
			$prepare_data['bargainor_id'] = $bargainor_id;
			$prepare_data['transaction_id'] = $transaction_id;
			$prepare_data['sp_billno'] = $sp_billno;
			$prepare_data['total_fee'] = $total_fee;
			$prepare_data['fee_type'] = $fee_type;
			$prepare_data['return_url'] = $return_url;
			$prepare_data['attach'] = $attach;
			$prepare_data['spbill_create_ip'] = $spbill_create_ip;
			$prepare_data['desc'] = $desc;
			$prepare_data['bank_type'] = $bank_type;
			$prepare_data['cs'] = $cs;		
			$prepare_data['sign'] = tenpay_build_mysign($prepare_data,$key,'MD5');
			$prepare_data = ten_arg_sort($prepare_data);
		}
		// 数字签名
		
		return $prepare_data;
	}
	
	/**
	 * GET接收数据
	 * 状态码说明  （0 交易完成 1 交易失败 2 交易超时 3 交易处理中 4 交易未支付5交易取消6交易发生错误）
	 */
    public function receive() {
		
    	$receive_sign = strtolower($_GET['sign']);
    	$receive_data = $this->filterParameter($_GET);
    	$receive_data = ten_arg_sort($receive_data);
		//print_r($receive_data);
		//echo '<br>'.$receive_sign.'<br>';
		
		
    	if ($receive_data) {
			$sign = '';
			if($this->config['service_type_ten']==0)//担保交易
			{
				$sign = isTenpaySign_2($receive_data,$this->config['tenpay_key'],'MD5');
			}
			else
			{
				$sign = isTenpaySign($receive_data,$this->config['tenpay_key'],'MD5');
			}
			if ($sign != $receive_sign)
			{
				error_log(date('m-d H:i:s',SYS_TIME).'| GET: signature is bad |'."\r\n", 3, CACHE_PATH.'pay_error_log.php');					
				showmessage(L('illegal_sign'));
				return false;
			}
			else
			{
				if($this->config['service_type_ten']==0)//担保交易
				{
					$return_data['order_id'] = $receive_data['attach'];
				
					if($receive_data['status']=='3' && $receive_data['retcode']=='0')
					{
						 $return_data['order_status'] = 0;						
					}
				}
				else
				{
					$return_data['order_id'] = $receive_data['attach'];
				
					if($receive_data['pay_result']==0 && $receive_data['pay_info']=='OK')
					{
						 $return_data['order_status'] = 0;						
					}
				}
				
				//print_r($return_data);exit;	
				return $return_data;
			}
		} else {
			
			error_log(date('m-d H:i:s',SYS_TIME).'| GET: no return |'."\r\n", 3, CACHE_PATH.'pay_error_log.php');
			showmessage(L('illegal_return'));
			return false;
		}   	
    }	

    /**
	 * POST接收数据
	 * 状态码说明  （0 交易完成 1 交易失败 2 交易超时 3 交易处理中 4 交易未支付 5交易取消6交易发生错误）
	 */
    public function notify() {
    	$receive_sign = $_POST['sign'];
    	$receive_data = $this->filterParameter($_POST);
    	$receive_data = arg_sort($receive_data);
    	if ($receive_data) {
			$verify_result = $this->get_verify('http://notify.tenpay.com/trade/notify_query.do?service=notify_verify&partner=' . $this->config['tenpay_partner'] . '&notify_id=' . $receive_data['notify_id']);
			if (preg_match('/true$/i', $verify_result))
			{
				$sign = '';
				$sign = build_mysign($receive_data,$this->config['tenpay_key'],'MD5');				
				if ($sign != $receive_sign)
				{
					error_log(date('m-d H:i:s',SYS_TIME).'| POST: signature is bad |'."\r\n", 3, CACHE_PATH.'pay_error_log.php');					
					return false;
				}
				else
				{
					$return_data['order_id'] = $receive_data['out_trade_no'];
					$return_data['order_total'] = $receive_data['total_fee'];
					$return_data['price'] = $receive_data['price'];
					switch ($receive_data['trade_status']) {
						case 'WAIT_BUYER_PAY': $return_data['order_status'] = 3; break;
						case 'WAIT_SELLER_SEND_GOODS': $return_data['order_status'] = 3; break;
						case 'WAIT_BUYER_CONFIRM_GOODS': $return_data['order_status'] = 3; break;
						case 'TRADE_CLOSED': $return_data['order_status'] = 5; break;						
						case 'TRADE_FINISHED': $return_data['order_status'] = 0; break;
						case 'TRADE_SUCCESS': $return_data['order_status'] = 0; break;
						default:
							 $return_data['order_status'] = 5;
					}
					return $return_data;
				}

			}
			else
			{
				error_log(date('m-d H:i:s',SYS_TIME).'|  POST: illegality notice : flase |'."\r\n", 3, CACHE_PATH.'pay_error_log.php');
				return false;
			}
		} else {
			
			error_log(date('m-d H:i:s',SYS_TIME).'|  POST: no post return |'."\r\n", 3, CACHE_PATH.'pay_error_log.php');
			return false;
		}   	
    }
    	
    /**
     * 相应服务器应答状态
     * @param $result
     */
    public function response($result) {
    	if (FALSE == $result) echo 'fail';
		else echo 'success';
    }
    
    /**
     * 返回字符过滤
     * @param $parameter
     */
	private function filterParameter($parameter)
	{
		$para = array();
		foreach ($parameter as $key => $value)
		{
			if ('sign' == $key || 'sign_type' == $key || '' == $value || 'm' == $key  || 'a' == $key  || 'c' == $key   || 'code' == $key ) continue;
			else $para[$key] = $value;
		}
		return $para;
	}
}
?>